<?php

namespace App\Http\Controllers\Admin;

use App\Model\Article;
use App\Model\Cate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Image;
use Markdown;
use App\Services\OSS;
use Illuminate\Support\Facades\Redis;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        //定义一个变量存放所有文章记录
        $arts = [];

        //1.判断redis中是否存在要去的文章
        $listkey = 'LIST:ARTICLE';
        $haskey = 'HASH:ARTICLE';
        //Redis::Flushall();
        if(Redis::exists($listkey)){
            //存放所有要获取的文章id
            $lists = Redis::lrange($listkey,0,-1);

            foreach ($lists as $k=>$v){
                $arts[] = Redis::hgetall($haskey.$v);
            }
            //dd($lists);
            //dd($arts);
        }else{
            //2.查询数据库，取出文章
            $arts =Article::get()->toArray();
            //3.存入redis中
            foreach ($arts as $k=>$v){
                //将文章id添加到$listkey中
                Redis::rpush($listkey,$v['art_id']);
                //将文章添加到$haskey中
                Redis::hmset($haskey.$v['art_id'],$v);
            }
        }
        //4.返回数据
        return view("admin.article.list",compact("arts"));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {

        $cate = (new Cate())->tree();
        return view("admin.article.add",compact("cate"));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //新增
        $res = Article::create($request->except("_token","photo"));
        Redis::Flushall();
        //dd($res);
        if($res){
            $data = [
                'status' => 0,
                'message'=> '新增成功！'
            ];
        }else{
            $data = [
                'status' => 1,
                'message'=> '新增失败！'
            ];
        }
        //json_decode();
        return $data;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $cate = (new Cate())->tree();
        $art = Article::find($id);
        return view("admin.article.edit",compact("art","cate"));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //1.根据id修改值
        $res = Article::where("art_id",$request->input("art_id"))->update($request->except("_token","art_id","photo"));
        Redis::Flushall();
        if($res){
            $data = [
                'status' => 0,
                'message'=> '修改成功！'
            ];
        }else{
            $data = [
                'status' => 1,
                'message'=> '修改失败！'
            ];
        }
        //json_decode();
        return $data;

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $art = Article::find($id);
        $res = $art->delete();
        Redis::Flushall();
        if($res){
            $data = [
                'status' => 0,
                'message' => '删除成功！'
            ];
        }else{
            $data = [
                'status' => 1,
                'message' => '删除失败！'
            ];
        }
        return $data;
    }

    //文章多删除
    public function delAll(Request $request){
        $input = $request->input("ids");

        $res = Article::destroy($input);
        Redis::Flushall();
        if($res){
            $data = [
                'status' => 0,
                'message'=> '删除成功！'
            ];
        }else{
            $data = [
                'status' => 1,
                'message'=> '删除失败！'
            ];
        }
        //json_decode();
        return $data;
    }


    //文件上传
    public function upload(Request $request){
        //获取上传文件
        $file = $request->file('photo');
        //判断上传文件是否成功
        if(!$file->isValid()){
            return response()->json(['ServerNo'=>'400','ResultData'=>'无效的上传文件！']);
        }

        //获取源文件的扩展名
        $ext = $file->getClientOriginalExtension();

        //新的文件名
        $newName = md5(time().rand(10000,99999)).'.'.$ext;
        //文件上传的指定路径
        $path = public_path('uploads');

        //将文件从临时目录移动到制定目录
//        if(!$file->move($path,$newName)){
//            return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败！']);
//        }


//        $res = Image::make($file)->resize(190,110)->insert('./uploads/c6be4177505ba8e655b1fc27c3b4a641.jpg')->save($path.'/'.$newName);
//        if($res){
//            //如果成功
//            return response()->json(['ServerNo'=>'200','ResultData'=>$newName]);
//        }else{
//            return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败！']);
//        }

        // 在外网上传一个文件并指定 options 如：Content-Type 类型
        //将文件移动到阿里云的OSS指定仓库
        $res = OSS::publicUpload('myblog2020428', $newName, $file->getRealPath(), [
            'ContentType' => 'application/jpg',
        ]);

        if($res){
            //如果成功
            return response()->json(['ServerNo'=>'200','ResultData'=>$newName]);
        }else{
            return response()->json(['ServerNo'=>'400','ResultData'=>'保存文件失败！']);
        }
    }

    //处理markdown内容转换为Html内容
    public function pre_markdown(Request $request){
        return Markdown::convertToHtml($request->cont);
    }

}
